package org.example.ExceptionHandler;

import lombok.extern.slf4j.Slf4j;
import org.example.common.CategoryException;
import org.example.common.OwnException;
import org.example.domain.R;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;

@Slf4j
@RestControllerAdvice
@ControllerAdvice
public class ExceptionHandlerconfig {
    @ExceptionHandler(Exception.class)
    public R<String> handler(SQLException e) {
        if (e.getMessage().contains("Duplicate entry")) {
            String[] split = e.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return R.error(msg);
        }
        System.out.println(e.getMessage());
        return R.error("未知错误");
    }

    @ExceptionHandler(CategoryException.class)
    public R<String> handler(CategoryException e) {
        return R.error(e.getMessage());
    }

    @ExceptionHandler(value = OwnException.class)
    public R msgExceptionHandler(HttpServletRequest request, OwnException ex) {
        log.error("OwnException:", ex);
        return R.error(ex.getCode() + ex.getMessage());
    }

}
